package com.yurun.loginmodule.controller;

import com.yurun.commonapi.api.CommonResult;
import com.yurun.commonapi.pojo.*;
import com.yurun.commonapi.vo.ParentVO;
import com.yurun.loginmodule.mapper.AdminMapper;
import com.yurun.loginmodule.mapper.RoleMapper;
import com.yurun.loginmodule.service.UmsAdminService;
import com.yurun.loginmodule.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import java.math.BigInteger;
import java.util.*;

@Api(tags = "登录模块")
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UmsAdminService adminService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation(value = "登录以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@RequestBody Employee employee) { //, BindingResult result
        String realPassword = adminMapper.getPassword(employee.getEmployeeId());
        if (realPassword == null) {
            return CommonResult.failed("用户名错误或用户已停用");
        } else if (!realPassword.equals(DigestUtils.md5DigestAsHex(employee.getEmployeePwd().getBytes()))) {
            return CommonResult.failed("密码错误");
        } else {

            //获得该用户角色
            String role = roleMapper.getRoleListByRoleId(employee.getEmployeeId()).get(0);
            // 获取用户机构id、分店id
            Employee employee1 = adminMapper.getOrgIdAndBranchId(employee.getEmployeeId());
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", JWTUtil.createToken(String.valueOf(employee.getEmployeeId()), role, String.valueOf(employee1.getOrganizationId()), String.valueOf(employee1.getBranchId()), String.valueOf(-4444)));
            tokenMap.put("tokenHead", tokenHead);
//            System.out.println(employee1);
            return CommonResult.success(tokenMap);
        }
    }

    @ApiOperation(value = "登录以后返回token")
    @RequestMapping(value = "/loginStudent", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult loginStudent(@RequestBody ParentVO parentVO) {
//        System.out.println(parentVO);
        List<ParentStudentRelation> parentPassword = adminMapper.getParentPwd(parentVO.getStudentPhone());
//        System.out.println(parentPassword);
//        String fatherPassword = adminMapper.getFatherPwd(studentPhone);
        Map<String, String> tokenMap = new HashMap<>();
        String StudentId = "";
        String OrganizationId = "";
        String BranchId = "";

        for (ParentStudentRelation psr : parentPassword) {
            if (!psr.getPassword().equals("") && psr.getPassword().equals(DigestUtils.md5DigestAsHex(parentVO.getStudentPwd().getBytes()))) {
                StudentId = StudentId + String.valueOf(psr.getStudentId()) + ",";
                OrganizationId = String.valueOf(psr.getOrganizationId());
                BranchId = String.valueOf(psr.getBranchId());
            }
            else {
                return CommonResult.failed("手机号或密码错误");
            }
        }
        tokenMap.put("token", JWTUtil.createToken(StudentId, "家长", OrganizationId, BranchId,String.valueOf(parentVO.getStudentPhone())));
            tokenMap.put("tokenHead", tokenHead);
            return CommonResult.success(tokenMap);
//        if (!parentPassword.getPassword().equals("") && parentPassword.getPassword().equals(DigestUtils.md5DigestAsHex(parentVO.getStudentPwd().getBytes()))) {
//            // 获取用户机构id、分店id
////            StudentDocument studentDocument = adminMapper.getStudentOrgIdAndBranchId(studentPhone);
//
//            Map<String, String> tokenMap = new HashMap<>();
//            //为了方便，直接给家长一个教师角色
//            tokenMap.put("token", JWTUtil.createToken(String.valueOf(parentPassword.getStudentId()), "家长", String.valueOf(parentPassword.getOrganizationId()), String.valueOf(parentPassword.getBranchId()),String.valueOf(parentVO.getStudentPhone())));
//            tokenMap.put("tokenHead", tokenHead);
//            return CommonResult.success(tokenMap);
//        } else {
//            return CommonResult.failed("手机号或密码错误");
//        }
    }

    @ApiOperation(value = "获取当前登录用户信息", notes = "包含用户的菜单")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAdminInfo(ServletRequest request) {
        String token = WebUtils.toHttp(request).getHeader("Authorization");
        String employeeId = JWTUtil.getUsername(token.substring(6));
        Employee umsAdmin = adminService.getAdminByUsername(BigInteger.valueOf(Long.parseLong(employeeId)));
        Map<String, Object> data = new HashMap<>();
        data.put("username", umsAdmin.getEmployeeName());
        data.put("menus", adminService.getMenu(BigInteger.valueOf(Long.parseLong(employeeId))));
        data.put("roles", "超级管理员");
        data.put("icon", umsAdmin.getEmployeeIcon());
        return CommonResult.success(data);
    }

    @ApiOperation(value = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success("退出成功!");
    }

    @ApiOperation(value = "修改密码")
    @RequestMapping("/resetPwd")
    public CommonResult resetPwd(Employee employee) {
        return adminService.resetPwd(employee);
    }

    @ApiOperation(value = "修改员工信息")
    @RequestMapping("/editEmployeeInfo")
    public CommonResult editEmployeeInfo(Employee employee) {
        return adminService.editEmployeeInfo(employee);
    }

}
